//
//  SearchDeliveryWarehouseView.swift
//  GreenDeal
//
//  Created by Moennig Q on 2023/5/10.
//

import UIKit
import SnapKit
import RxCocoa
import RxSwift
import RxGesture
class SearchDeliveryWarehouseView: UIView {
    fileprivate lazy var disposeBag = DisposeBag()
    private var searchValue: String = ""
    //
    private var searchAddressTye: DeliveryWarehouseType = .OSW
    var selectClosure: ((DeliveryWarehouseModel)->Void)?
    let searchTopView = SearchTopView(bgImageName: "createjob_installation_address_top_bg")
    let tableView = TableView()
    var list = [DeliveryWarehouseModel]()
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUpView()
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    init(deliveryWarehouseType: DeliveryWarehouseType ) {
        super.init(frame: CGRect.zero)
        self.searchAddressTye = deliveryWarehouseType
        setUpView()
    }
    private func setUpView() {
        self.backgroundColor = .white
        var placeHolder: String = ""
        if self.searchAddressTye == .OSW {//osw delivery warehouse
            placeHolder = R.string.localizable.selectOSWWarehouseAddress()
        }else if self.searchAddressTye == .other {//other delivery warehouse
            placeHolder = R.string.localizable.selectPickUpAddress()
        }
        self.searchTopView.searchTextfield.placeholder = placeHolder
        self.addSubview(searchTopView)
        searchTopView.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
            make.height.greaterThanOrEqualTo(0)
        }
        //
        self.tableView.separatorStyle = UITableViewCell.SeparatorStyle.none
        self.tableView.showsVerticalScrollIndicator = false
        //防止上拉加载时数据滚动
        self.tableView.estimatedRowHeight = 200
        self.tableView.rowHeight = UITableView.automaticDimension
        //
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(SearchAddressCell.self, forCellReuseIdentifier: SearchAddressCell.reuseCellIdentifier)
        
        self.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(searchTopView.snp.bottom)
            make.left.right.equalToSuperview()
            make.height.greaterThanOrEqualTo(0)
            make.bottom.equalToSuperview()
        }
        //
        self.searchTopView.cancelLabel.rx.tapGesture().when(.recognized).subscribe(onNext: { [weak self] _ in
            self?.removeFromSuperview()
        }).disposed(by: self.disposeBag)
        self.searchTopView.searchTextfield.rx.controlEvent(.editingDidEndOnExit).subscribe { [weak self] _ in
            guard let strongSelf = self else {return }
            guard let searchText = strongSelf.searchTopView.searchTextfield.text , searchText.trimmingCharacters(in: .whitespaces) != "" else {return}
            strongSelf.getDeliverWarehouseList()
        }.disposed(by: self.disposeBag)
        //
        self.searchTopView.editingChangedClosure = {[weak self] in
            self?.getDeliverWarehouseList()
        }
        tableView.loadFaildView.retryBtn.addTarget(self, action: #selector(retryBtnClick), for: UIControl.Event.touchUpInside)
        //初始获取全部warehouse数据
        self.getDeliverWarehouseList()
    }
    @objc private func retryBtnClick(){
        self.getDeliverWarehouseList()
    }
    
    @objc func closeBtnClick(){
        self.removeFromSuperview()
    }
    //MARK: - 根据search value获取address list
    private func getDeliverWarehouseList(){
        self.searchValue = (self.searchTopView.searchTextfield.text ?? "").trimmingCharacters(in: .whitespaces)
        let vm = DictionaryService()
        vm.setBlockAfterNetwork { [weak self] (result, _) in
            guard let strongSelf = self else {return}
            ModelViewUtil.shared.hideLoadingView()
            strongSelf.list.removeAll()
            if let list = result as? Array<DeliveryWarehouseModel>{
                var realList = list
                if strongSelf.searchValue.count > 0{//如果有过滤条件，自己过滤
                    realList = list.filter({$0.address_text.contains(strongSelf.searchValue)})
                }
                strongSelf.list = realList
                strongSelf.tableView.reloadData()
            }
            //没有数据显示not data view，有数据隐藏not data view
            strongSelf.tableView.showResultView(nodataFlag: strongSelf.list.count == 0 ? true: false)
        } errorBlock: { [weak self] (code, error) in
            guard let strongSelf = self else {return}
            ModelViewUtil.shared.hideLoadingView()
            strongSelf.list.removeAll()
            strongSelf.tableView.reloadData()
            strongSelf.tableView.showRetryView()
            Tool().showAlertViewWithOneBtn(message: error)
        }
        ModelViewUtil.shared.showLoadingView(parentView: self)
        if self.searchAddressTye == .OSW{//搜索osw的warehouse
            vm.getDeliveryList(deliveryWarehouseType: .OSW, companyID: CreateJobModelHelper.shared.createJobViewModel.summaryViewModel.company_id)
        }else if self.searchAddressTye == .other{//搜索other的warehouse
            vm.getDeliveryList(deliveryWarehouseType: .other, companyID: CreateJobModelHelper.shared.createJobViewModel.summaryViewModel.company_id)
        }
    }
}
extension SearchDeliveryWarehouseView: UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.list.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: SearchAddressCell.reuseCellIdentifier) as? SearchAddressCell
        if cell == nil {
            cell = SearchAddressCell(style: .default, reuseIdentifier: SearchAddressCell.reuseCellIdentifier)
        }
        cell!.setData(self.list[indexPath.row].address_text)
        return cell!
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.selectClosure?(self.list[indexPath.row])
        self.removeFromSuperview()
    }
    //
    func textFieldDidEndEditing(_ textField: UITextField) {
        self.getDeliverWarehouseList()
    }
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        self.endEditing(true)
        return true
    }
}
